<template>
    <div>
        <div class="box">
            <div class="top">
                <div class="top_left">
                    <span style="font-family: 'KaiTi';font-size: 16px;">设置我的昵称</span>
                </div>
                <div class="top_right" @click="ShowLoginDiv">
                    <!-- <svg t="1683716393871" class="icon" viewBox="0 0 1024 1024" version="1.1"
						xmlns="http://www.w3.org/2000/svg" p-id="5245" width="200" height="200">
						<path
							d="M557.311759 513.248864l265.280473-263.904314c12.54369-12.480043 12.607338-32.704421 0.127295-45.248112-12.512727-12.576374-32.704421-12.607338-45.248112-0.127295L512.127295 467.904421 249.088241 204.063755c-12.447359-12.480043-32.704421-12.54369-45.248112-0.063647-12.512727 12.480043-12.54369 32.735385-0.063647 45.280796l262.975407 263.775299-265.151458 263.744335c-12.54369 12.480043-12.607338 32.704421-0.127295 45.248112 6.239161 6.271845 14.463432 9.440452 22.687703 9.440452 8.160624 0 16.319527-3.103239 22.560409-9.311437l265.216826-263.807983 265.440452 266.240344c6.239161 6.271845 14.432469 9.407768 22.65674 9.407768 8.191587 0 16.352211-3.135923 22.591372-9.34412 12.512727-12.480043 12.54369-32.704421 0.063647-45.248112L557.311759 513.248864z"
							fill="#707070" p-id="5246"></path>
					</svg> -->
                </div>
            </div>
            <div class="content">
                <div v-show="IsShowLoginUserImg" @click="SetImg()">
                    <input ref="inputfile" type="file" accept="image/*" @change="handleFileChange" name="" id="fi" value=""
                        style="display: none;" />
                    <svg v-if="LoginUserImg == ''" style="width: 80px;height: 80px;" t="1687157286301" class="icon"
                        viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="22407" width="200"
                        height="200">
                        <path
                            d="M512.3 106c-223.6 0-406.7 183-406.7 406.7s183 406.6 406.7 406.6 406.6-183 406.6-406.7C919 289 736 106 512.3 106z m10.2 122c155 0 155 116.9 155 183s-61 188.1-155 190.6c-91.5 0-155-122-155-190.6 0-66.1 0-183 155-183z m-10.2 668.4c-116.9 0-223.7-53.4-294.8-137.2 10.2-25.4 22.9-53.4 40.7-68.6 38.1-30.5 152.5-81.3 152.5-81.3l71.2 137.2 12.7-33-20.4-40.7 40.7-40.7 40.7 40.7-17.9 43.2 10.2 33.1 73.7-134.7s114.4 50.8 152.5 81.3c17.8 12.7 30.5 35.6 38.1 55.9-68.6 88.9-177.9 144.8-299.9 144.8z m0 0"
                            p-id="22408"></path>
                    </svg>
                    <div v-else
                        style="border: 3px solid #eee;border-radius: 50%;overflow: hidden;display: flex;align-items: center;justify-content: center;margin-bottom: 9px;">
                        <img :src="LoginUserImg" alt="" style="width: 56px;height: 56px;">
                    </div>
                </div>
                <input v-show="IsShowUserNameAndPwd" v-model="UserName" type="text" placeholder="唯一昵称 (只能设置一次)"
                    :style="`width: 80%;height: 30px;margin-top:${IsShowLoginUserImg ? '5px':'25px'};border-radius: 5px;outline: none;border: 1px solid darkgray;padding-left: 7px;font-family: Kaiti;`">
                    
                    <input v-show="IsShowUserNameAndPwd" v-model="UserPassWord" type="text" placeholder="密码 (方便其他设备登入)"
                    style="width: 80%;height: 30px;margin-top: 5px;border-radius: 5px;outline: none;border: 1px solid darkgray;padding-left: 7px;font-family: Kaiti;">
                
                    <button class="loginbtn" @click="ShowLoginDiv">设置</button>
            </div>
        </div>
    </div>
</template>

<script>
import axios from "axios";
export default {
    data() {
        return {
            Useruuid:'',
            UserName: '',
            UserPassWord:'',
            LoginUserImg: '',
            IsShowLoginUserImg:false,
            IsShowUserNameAndPwd:true,
        }
    },
    mounted() {
        if(localStorage.getItem('cacheLoginUserName') != null)
        {
            this.UserName = localStorage.getItem('cacheLoginUserName')
        }
        if(localStorage.getItem('cacheLoginUserImg') != null)
        {
            this.LoginUserImg = localStorage.getItem('cacheLoginUserImg')
        }

        if(localStorage.getItem('cacheUserPassWord') != null)
        {
            this.UserPassWord = localStorage.getItem('cacheUserPassWord')
        }

        if(localStorage.getItem("cacheLoginuuid") != null)
        {
            this.Useruuid = localStorage.getItem('cacheLoginuuid')
        }


       
         
    },
    methods: {
        SetImg() {
            this.$refs.inputfile.dispatchEvent(new MouseEvent("click"));
        },

        async handleFileChange(e) {

            return await new Promise(async (resolve, reject)=> {
                //let file = e.target.files;
                let filename = ''
                let filetype = ''
                let file = e.target.files[0];
                filename = file.name
                filetype = file.type 

                let prefilename = file.name

                let fileSizeInKB = Math.round(file.size / 1024);
                //console.log('默认size', fileSizeInKB);

                if (fileSizeInKB > 500 && fileSizeInKB <= 1000) {
                    file = await this.CanvascompressImage(e.target.files[0], 0.6, 1920, 1080);
                    fileSizeInKB = Math.round(file.size / 1024);
                    //console.log('压缩后size1', fileSizeInKB);
                }
                else if (fileSizeInKB > 1000 && fileSizeInKB <= 1500) {
                    file = await this.CanvascompressImage(e.target.files[0], 0.5, 1920, 1080);
                    fileSizeInKB = Math.round(file.size / 1024);
                    //console.log('压缩后size2', fileSizeInKB);
                }
                else if (fileSizeInKB > 1500) {
                    file = await this.CanvascompressImage(e.target.files[0], 0.4, 1920, 1080);
                    fileSizeInKB = Math.round(file.size / 1024);
                    //console.log('压缩后size3', fileSizeInKB);
                }
                // let reader = new FileReader();
                // reader.readAsDataURL(file);
                // reader.onload = () => {
                //     let dataURL = reader.result;
                //     this.LoginUserImg = dataURL
                // }; 

                const fileddl = new File([file], filename, { type: filetype });
                // 创建FormData对象 
                var formData = new FormData();
                // 添加文件到formData对象中 
                formData.append('foldername', 'userimgs_2');
                formData.append('filename', prefilename);
                formData.append('useruuid', this.Useruuid);
                formData.append('file', fileddl);
                // 发送POST请求 
                //url: 'https://api.xiaoshagua.top/api/File/Upload',
                axios.post(this.$BaseUrl+'/api/File/Upload', formData).then(res => {
                    this.LoginUserImg = res.data.data

                    
                    this.$emit('child-SetChildLoginUserImg', this.LoginUserImg);
                    resolve(this.LoginUserImg );

                }).catch(error => {
                    reject(error)
                    console.log(error);
                });

            })

        },
        CanvascompressImage(file, thisquality, maxWidth, maxHeight) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    let width = img.width;
                    let height = img.height;

                    if (width > maxWidth) {
                        height *= maxWidth / width;
                        width = maxWidth;
                    }

                    if (height > maxHeight) {
                        width *= maxHeight / height;
                        height = maxHeight;
                    }

                    canvas.width = width;
                    canvas.height = height;

                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, width, height);

                    canvas.toBlob(
                        blob => {
                            resolve(blob);
                        },
                        file.type,
                        thisquality // 压缩质量，可以根据需要调整
                    );
                };

                img.onerror = reject;

                img.src = URL.createObjectURL(file);
            });
        },
        ShowLoginDiv() {
            // if (this.LoginUserImg == '') {
            //     this.$emit('child-Tips', '请选择一个头像!');
            //     return
            // }
            if (this.UserName == '') {
                this.$emit('child-Tips', '昵称不能为空!');
                return
            }
            if (this.UserPassWord == '') {
                this.$emit('child-Tips', '密码不能为空!');
                return
            }

            
            let loginobj = 
            {
                useruuid:this.Useruuid,
                username:this.UserName,
                password:this.UserPassWord,
                userimgurl:this.LoginUserImg
            }
            axios.post(this.$BaseUrl + '/api/ChatGPT/PreLogin',loginobj)
            .then(async res => {
                console.log('then',res.data);
             if(res.data.data != null)
             { 
                if(res.data.data.userimgurl == '')
                {
                    this.Useruuid = res.data.data.useruuid
                    this.IsShowLoginUserImg = true
                    this.$emit('child-Tips', '检测你第一次使用，请选择你的头像');
                    return
                }

                localStorage.setItem("cacheUserPassWord", this.UserPassWord);

                let obj = {
                Loginuuid:res.data.data.useruuid,
                UserName: res.data.data.username,
                LoginUserImg: res.data.data.userimgurl,
                IsVip:res.data.data.isvip
                }
                
                this.$emit('child-ShowLoginDiv', obj);
             }
             else
             {
                console.log('err',res.data);
                this.$emit('child-Tips', res.data.msg);
             }

            }).catch(error => {

            console.error(error);
            });

            
            
        },
        Copy(tit) {
            //提示

            this.$emit('child-Tips', 111);


            const data = tit.trim();
            //const data = 'Hello, world!'
            this.$copyText(data).then(function () {
                console.log('Copied:', data)
            }, function () {
                console.error('Copy failed:', data)
            })
        }
    }
}
</script>

<style scoped>
.box {
    background-color: #e6e5e5;
    border: 1px solid #636363;
    display: flex;
    /* height: 265px; */
    box-sizing: border-box;
    flex-direction: column;
    z-index: 9999999;
    padding: 10px;
    padding-bottom: 20px;
    border-radius: 6px;
    box-shadow: 0 0 10px 1px #888888;
    font-family: 'KaiTi';
}



.top {
    display: flex;
    justify-content: space-between;
    font-size: 15px;
    font-weight: 600;

}

.top_right:hover {
    cursor: pointer;
}

.top_right svg {
    width: 22px;
    height: 22px;
    font-weight: 700;
    margin-right: 2px;
}

.content {
    overflow: auto;
    display: flex;
    flex-direction: column;
    align-items: center;

}

.content::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 3px;
    /*滚动条整体宽度*/
    /*height: 1100px;*/
    /*scrollbar-arrow-color:red;*/
}

.content::-webkit-scrollbar-thumb {
    /*滚动条里面的小方块*/
    border-radius: 10px;
    /*-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);*/
    background-color: #c3c4c6;
    /*滚动条颜色*/
}

.content::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    /*-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);*/
    /*border-radius: 5px;*/
    /*滚动条背景颜色*/
}

/* 火狐 */
/* Firefox 64及以上版本 */
.content {
    scrollbar-width: none;
}

.loginbtn {
    background-color: #129611;
    width: 130px;
    height: 30px;
    line-height: 30px;
    border: 0;
    color: #fff;
    border-radius: 4px;
    font-size: 14px;
    font-family: "KaiTi";
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 22px;
}

.loginbtn:hover {
    cursor: pointer;
}
</style>